package per.turtle.gen.controller;

import cn.hutool.core.convert.Convert;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.core.web.page.TableDataInfo;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.gen.domain.GenTable;
import per.turtle.gen.domain.GenTableColumn;
import per.turtle.gen.service.IGenTableColumnService;
import per.turtle.gen.service.IGenTableService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/gen")
@RequiredArgsConstructor
@RestController
@Tag(name = "gen", description = "gen_代码生成")
public class GenController extends BaseController {

    private final IGenTableService genTableService;

    private final IGenTableColumnService genTableColumnService;

    @Operation(summary = "批量生成代码", description = "批量生成代码")
    @PreAuthorize(hasPermission = "tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    @Operation(summary = "查询数据表字段列表", description = "查询数据表字段列表")
    @GetMapping(value = "/column/{tableId}")
    public TableDataInfo<GenTableColumn> columnList(Long tableId) {
        List<GenTableColumn> list = startPage(s -> genTableColumnService.selectGenTableColumnListByTableId(tableId));
        return getDataTable(list);
    }

    @Operation(summary = "查询数据库列表", description = "查询数据库列表")
    @PreAuthorize(hasPermission = "tool:gen:list")
    @PostMapping("/db/list")
    public TableDataInfo<GenTable> dataList(@RequestBody GenTable genTable) {
        List<GenTable> list = startPage(s -> genTableService.selectDbTableList(genTable));
        return getDataTable(list);
    }

    @Operation(summary = "生成代码（下载方式）", description = "生成代码（下载方式）")
    @PreAuthorize(hasPermission = "tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    @Operation(summary = "修改保存代码生成业务", description = "修改保存代码生成业务")
    @PreAuthorize(hasPermission = "tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult<Void> editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return CommonResult.success();
    }

    @Operation(summary = "生成代码（自定义路径）", description = "生成代码（自定义路径）")
    @PreAuthorize(hasPermission = "tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public CommonResult<Void> genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return CommonResult.success();
    }

    @Operation(summary = "查询代码生成列表", description = "查询代码生成列表")
    @PreAuthorize(hasPermission = "tool:gen:list")
    @PostMapping("/list")
    public TableDataInfo<GenTable> genList(@RequestBody GenTable genTable) {
        List<GenTable> list = startPage(s -> genTableService.selectGenTableList(genTable));
        return getDataTable(list);
    }

    @Operation(summary = "修改代码生成业务", description = "修改代码生成业务")
    @PreAuthorize(hasPermission = "tool:gen:query")
    @GetMapping(value = "/{tableId}")
    public CommonResult<Map<String, Object>> getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return CommonResult.success(map);
    }

    @Operation(summary = "导入表结构（保存）", description = "导入表结构（保存）")
    @PreAuthorize(hasPermission = "tool:gen:import")
    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public CommonResult<Void> importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return CommonResult.success();
    }

    @Operation(summary = "预览代码", description = "预览代码")
    @PreAuthorize(hasPermission = "tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    public CommonResult<Map<String, String>> preview(@PathVariable("tableId") Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return CommonResult.success(dataMap);
    }

    @Operation(summary = "删除代码生成", description = "删除代码生成")
    @PreAuthorize(hasPermission = "tool:gen:remove")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public CommonResult<Void> remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return CommonResult.success();
    }

    @Operation(summary = "同步数据库", description = "同步数据库")
    @PreAuthorize(hasPermission = "tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/syncDb/{tableName}")
    public CommonResult<Void> syncDb(@PathVariable("tableName") String tableName) {
        genTableService.syncDb(tableName);
        return CommonResult.success();
    }

    @Operation(summary = "生成zip文件", description = "生成zip文件")
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"turtle-gen.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
